home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news!enno
- From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
- Newsgroups: comp.lang.c++
- Subject: Re: novice question on copy constru
- Date: 28 Jan 1996 15:15:59 GMT
- Organization: Fachbereich Informatik, TH Darmstadt
- Distribution: world
- Message-ID: <ENNO.96Jan28161559@kitz.inferenzsysteme.informatik.th-darmstadt.de>
- References: <4efpie$jsq@news.ust.hk>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- In-reply-to: ee_ckmaa@uxmail.ust.hk's message of 28 Jan 1996 12:18:22 GMT
-
- In article <4efpie$jsq@news.ust.hk> ee_ckmaa@uxmail.ust.hk (Chan Ka Ming) writes:
-
- I don't understand why one should create a copy constructor. Doesn't the
- computer will do the job for you when pass arguments by value? Thanks
-
- If you don't define a copy-constructor the compile will provide the
- 'default copy-constructor', which performs a 'memberwise' copy, ie.
- the appropriate copy-constructors of the base-classes and non-static
- data-members are called. Unfortunately this behavior is not suitable
- for all situations. For example in the following class memberwise
- copying is not the right solution
-
- struct A {
- int* i_;
- A() : i_(new int(4711)) {}
- ~A() { delete i_; }
- };
-
- because only the pointer-value and not the related data is copied.
- Thus in the subsequent snippet
-
- A a1;
- A a2(a1);
-
- 'a1' and 'a2' share the same data, which will be therefore released
- two times. This problem can easily removed by adding an appropriate
- copy-constructor (cc). Similar problems could occur when you assign
- an existing object to another. So an additional assignment-operator
- (as) is also a good idea. The modified class looks like:
-
- struct A {
- int* i_;
- A() : i_(new int(4711)) {}
- A(const A& a) : i_(new int(*a.i_)) {} // (cc)
- A& operator = (const A& a) { // (as)
- if (this!=&a) { delete i_; i_=new int(*a.i_); }
- return *this;
- }
- ~A() { delete i_; }
- };
-
- After this change 'A' has 'proper copy-semantics'. You can use it in
- other classes and don't have to care about how objects of 'A' are
- copied -- the compiler creates the necessary code for calling the (cc)
- or (as). For example the class 'B' defined as
-
- struct B { A a_; };
-
- has also proper copy-semantics because the default-versions of (cc)
- and (as) do memberwise _not_ bitwise copy of the single data-member.
-
- Enno
-